# coding=utf-8

from flask_migrate import Migrate, MigrateCommand
from flask_script import Server, Shell, Manager, prompt_bool
from sqlalchemy import text

from apps import app
from apps.foundation import db, redis
from config import SECRET_KEY

app.debug = True
app.secret_key = SECRET_KEY
manager = Manager(app)

manager.add_command("runserver", Server('0.0.0.0', port=8000))


def _make_context():
    return dict(db=db)


manager.add_command("shell", Shell(make_context=_make_context))


@manager.command
def createall():
    db.create_all()
    db.session.commit()


@manager.command
def dropall(pass_ask=None):
    "Drops all database tables"
    if pass_ask:
        db.drop_all()
    else:
        if prompt_bool("Are you sure ? You will lose all your data !"):
            db.drop_all()


def clear_redis():
    redis.db.flushall()


@manager.command
def resetall(pass_ask=None):
    dropall(pass_ask)
    clear_redis()
    createall()


@manager.command
def delete_alembic():
    sql = text('DROP TABLE alembic_version;')
    db.engine.execute(sql)


migrate = Migrate(app, db)

manager.add_command('db', MigrateCommand)
if __name__ == "__main__":
    manager.run()
